package com.ruoyi.system.service.impl;

import com.ruoyi.common.OrderNumUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.app.Participation;
import com.ruoyi.system.domain.app.SysWithdraw;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.app.ParticipationMapper;
import com.ruoyi.system.mapper.app.SysWithdrawMapper;
import com.ruoyi.system.service.MoneyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.print.DocFlavor;
import java.beans.Transient;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class MoneyServiceImpl implements MoneyService {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    ParticipationMapper participationMapper;
    @Autowired
    SysWithdrawMapper sysWithdrawMapper;

    @Autowired
    RedisCache redisCache;


    @Override
    public List<Map<String, Object>> moneyList(String userName) {
        return sysUserMapper.moneyList(userName);
    }

    @Override
    public List<Participation> operatorMoneyList(Long operatorId,String orderNum) {
        return participationMapper.operatorMoneyList(operatorId,orderNum);
    }

    @Override
    public Map operatorMoneyIndex(Long operatorId) {
        return participationMapper.operatorMoneyIndex(operatorId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void withdraw(BigDecimal money, String realName, Integer remitType,String bankName,String number) {
        if (money.doubleValue() <= 0D) {
            throw new ServiceException("金额出错！");
        }
        if (money.doubleValue() > 5000d || money.doubleValue() <= 1d) {
            throw new ServiceException("提现金额不可大于5000元小于1元。");
        }
        SysWithdraw sysWithdraw = new SysWithdraw();
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getLoginUser().getUser().getUserId());
        if (sysUser.getWithdrawBalance().doubleValue() < money.doubleValue()) {
            throw new ServiceException("金额不足");
        }
        setInfo(remitType, sysWithdraw, bankName, number, null);
        sysUser.setBalance(sysUser.getBalance().subtract(money));
        sysUser.setWithdrawBalance(sysUser.getWithdrawBalance().subtract(money));
        sysUserMapper.updateUser(sysUser);

        sysWithdraw.setWithdrawNum(OrderNumUtil.getOrderNum());
        sysWithdraw.setSysId(sysUser.getUserId());
        sysWithdraw.setState(0);
        sysWithdraw.setType(1);
        sysWithdraw.setMoney(money);
        sysWithdraw.setRealName(realName);
        sysWithdraw.setCreateTime(new Date());
        sysWithdrawMapper.insertSelective(sysWithdraw);
        //添加到记录
        Participation participation = new Participation();
        participation.setParticipationState(2);
        participation.setSysId(sysWithdraw.getSysId());
        participation.setOrderNum(sysWithdraw.getWithdrawNum());
        participation.setOrderId(sysWithdraw.getId());
        participation.setType(3);
        participation.setMoney(money.negate());
        participation.setCreateTime(new Date());
        if (sysWithdraw.getRemitType() == 1) {
            participation.setRemark("提现方式:微信打款。提现金额：" + sysWithdraw.getMoney() + "元。提现账户：" + sysWithdraw.getRealName());
        } else {
            participation.setRemark("提现方式:银行卡打款。提现金额：" + sysWithdraw.getMoney() + "元。提现账户：" + sysWithdraw.getNumber());
        }
        participationMapper.insertSelective(participation);
    }

    @Override
    public List<SysWithdraw> withdrawList(String phone, String orderNum, Integer state) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.isAdmin()) {
            return sysWithdrawMapper.withdrawList(phone,orderNum,state,null);
        }else {
            return sysWithdrawMapper.withdrawList(phone, orderNum, state, sysUser.getUserId());
        }

    }

    @Override
    public void withdrawCheck(Long orderId, Integer type, String reason) {
        SysWithdraw sysWithdraw = sysWithdrawMapper.selectByPrimaryKey(orderId);
        Participation participation = participationMapper.getByOrderNum(sysWithdraw.getWithdrawNum());
        if (sysWithdraw.getState() != 0) {
            throw new ServiceException("此申请已处理");
        }

        if (type == 2) {
            if (sysWithdraw.getType() == 1) {
                SysUser operator = sysUserMapper.selectUserById(sysWithdraw.getSysId());
                operator.setBalance(operator.getBalance().add(sysWithdraw.getMoney()));
                operator.setWithdrawBalance(operator.getWithdrawBalance().add(sysWithdraw.getMoney()));
                sysUserMapper.updateUser(operator);
            }

            participation.setParticipationState(4);
            sysWithdraw.setState(2);
            sysWithdraw.setReason(reason);
            sysWithdraw.setWithdrawTime(new Date());
            sysWithdraw.setCheckSysId(SecurityUtils.getLoginUser().getUser().getUserId());
            sysWithdraw.setCheckName(SecurityUtils.getLoginUser().getUser().getUserName());
            sysWithdrawMapper.updateByPrimaryKeySelective(sysWithdraw);
            participationMapper.updateByPrimaryKeySelective(participation);
        }else {
            sysWithdraw.setCheckSysId(SecurityUtils.getLoginUser().getUser().getUserId());
            sysWithdraw.setCheckName(SecurityUtils.getLoginUser().getUser().getUserName());
            participation.setParticipationState(3);
            sysWithdraw.setState(1);
            participation.setParticipationTime(new Date());
            sysWithdraw.setWithdrawTime(new Date());
            //sysWithdrawMapper.updateByPrimaryKeySelective(sysWithdraw);
            sysWithdraw.setReason(reason);


//            //微信打款
//            if (sysWithdraw.getRemitType() ==1) {
//                //微信打款
//
//                //Map map1 = wxRemit(sysWithdraw.getId(),"shareWithdraw");
//                if ("SUCCESS".equals(map1.get("return_code")) && map1.get("err_code") == null) {
//                    log.info("收益提现:【{}】{}", sysWithdraw.getWithdrawNum(), "打款成功");
//                    sysWithdraw.setRemark((String) map1.get("payment_no"));
//                }
//                //打款失败
//                else {
//                    log.error("分享收益提现:【{}】{}", sysWithdraw.getWithdrawNum(), "打款失败");
//                    log.info(map1.toString());
//                    if ("NAME_MISMATCH".equals(map1.get("err_code"))) {
//                        sysWithdraw.setRemark("打款失败！请检查真实姓名是否一致.");
//                    }else if ("AMOUNT_LIMIT".equals(map1.get("err_code"))){
//                        sysWithdraw.setRemark(map1.get("err_code_des").toString());
//                    } else if ("MONEY_LIMIT".equals(map1.get("err_code"))) {
//                        sysWithdraw.setRemark(map1.get("err_code_des").toString());
//                    } else if ("PARAM_ERROR".equals(map1.get("err_code"))) {
//                        sysWithdraw.setRemark(map1.get("err_code_des").toString());
//                    } else {
//                        sysWithdraw.setRemark("打款失败！请检查平台余额或打款金额");
//                    }
//                        SysUser operator = sysUserMapper.selectUserById(sysWithdraw.getSysId());
//                        operator.setBalance(operator.getBalance().add(sysWithdraw.getMoney()));
//                        operator.setWithdrawBalance(operator.getWithdrawBalance().add(sysWithdraw.getMoney()));
//                        sysUserMapper.updateUser(operator);
//
//                    sysWithdraw.setState(2);
//                    participation.setParticipationState(4);
//                    participationMapper.updateByPrimaryKeySelective(participation);
//                }
//            }

            sysWithdraw.setWithdrawTime(new Date());
            sysWithdrawMapper.updateByPrimaryKeySelective(sysWithdraw);
            participationMapper.updateByPrimaryKeySelective(participation);
        }
    }

    @Override
    public void bindPhone(String phone, String code) {
        String redisCode = redisCache.getCacheObject("register:phone" + phone);
        if (StringUtils.isEmpty(redisCode) || !code.equals(redisCode)) {
            throw new ServiceException("验证码错误");
        }
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getLoginUser().getUser().getUserId());
        sysUser.setPhonenumber(phone);
        sysUserMapper.updateUser(sysUser);
    }

    private SysWithdraw setInfo(Integer remitType, SysWithdraw sysWithdraw, String bankName, String number, String openId) {
        if (remitType == 1) {
            sysWithdraw.setRemitType(1);
            sysWithdraw.setOpenid(openId);

        } else if (remitType == 2) {
            sysWithdraw.setRemitType(2);
            sysWithdraw.setBankName(bankName);
            sysWithdraw.setNumber(number);

        }
        return sysWithdraw;
    }

}
